<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Image;
use Log;
use Validator;
use Storage;

class Attachment extends Model
{
    protected $table = 'attachment';
    var $jsonData = ['code'=>0,'msg'=>'','data'=>[]];
    //图片名称
    var $uploadPicName = 'pic';
    //图片上传最大大小/kb
    var $picMaxSize = 2048;
    //base64图片
    var $isBase64 = false;
    //图片质量
    var $percent = 40;

    //文件名
    var $uploadFileName = 'file';
    //文件上传最大大小/kb
    var $fileMaxSize  = 5120;//5mb

    //视频名
    var $uploadVideoName = 'video';
    //视频上传最大大小/kb
    var $videoMaxSize  = 30720;//30mb

    //上传根目录名称
    var $rootName = '/upload/';
    var $timePath = '';
    var $setFileName = '';
    var $fileArea = '';

    function __construct(){
        $this->timePath = date('Y').'/'.date('m').'/'.date('d')."/".date('H').'/';
        $this->setFileName = date('YmdHis').str_random(15);
        parent::__construct();
    }


    /**
     * 上传图片
     * 包含对base64的图片处理
     * @param  [type] $request [description]
     * @return [type]          [description]
     */
    function uploadPic($request,$percent=null){
        $data = $request->all();
        $base64 = $request->input($this->uploadPicName);
        try {
            if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64, $result)){
                $file = base64_decode(str_replace($result[1], '', $base64));
                $this->isBase64 = true;
            }else{
                $validator = $this->picValidator($data);
                if($validator->fails()){
                    $this->jsonData['code'] = 1;
                    $this->jsonData['msg'] = $validator->errors()->first();
                    exit(json_encode($this->jsonData));
                }
                $file      = $request->file($this->uploadPicName);
            }
            $makeImg  = Image::make($file);
            $fileSize = round($makeImg->filesize()/1024);
            $fileType = $makeImg->mime();
            $extension = explode('/', $fileType)[1];

            if($fileSize>$this->picMaxSize){
                $this->jsonData['code'] = 1;
                $this->jsonData['msg'] = '图片上传过大,只允许'.($this->picMaxSize/1024).'mb内的图片';
                exit(json_encode($this->jsonData));
            }

            $this->fileArea = isset($data['fileArea']) ?  $data['fileArea'].'/' : '';

            $fileName        = $this->setFileName.'.'.$extension;
            $this->url       = $this->rootName.$this->fileArea.$this->timePath;
            $this->remoteUrl = '';
            $this->fileType  = $fileType;
            $this->fileName  = $fileName;
            $this->fileSize  = $fileSize;
            $this->width     = $makeImg->width();
            $this->height    = $makeImg->height();
            $this->isRemote  = 0;
            //创建目录
            if(!Storage::makeDirectory($this->fileArea.$this->timePath)){
                $this->jsonData['code'] = 1;
                $this->jsonData['msg'] = '创建图片目录失败,请重新上传';
                exit(json_encode($this->jsonData));
            }
            $image = $makeImg->save(public_path($this->url).$this->fileName,$percent ? $percent : $this->percent);
            $this->save();
            return $this;
        } catch (\Exception $e) {
            Log::error('【'.$e->getMessage().'】'.'【'.$e->getFile().'】'.'【'.$e->getTraceAsString ().'】');
            $this->jsonData['code'] = 1;
            $this->jsonData['msg'] = '图片上传异常';
            exit(json_encode($this->jsonData));
        }
    }

    /**
     * 根据图片地址上传图片
     * @param  [string] $url      [图片地址]
     * @param  [string] $fileName [图片名,不填写系统随机]
     * @return [type]           [description]
     */
    function downloadPicUrl($url,$fileName=''){
        try {
            $makeImg = Image::make($url);
            
            $fileSize = round(get_headers($url,true)['Content-Length']/1024);
            $fileType = $makeImg->mime();
            $extension = explode('/', $fileType)[1];
            if($fileName==''){
                $this->fileName = $this->setFileName.'.'.$extension;
            }else{
                $this->fileName = $fileName.'.'.$extension;
            }
            $this->url = $this->rootName.$this->fileArea.$this->timePath;
            $this->remoteUrl = '';
            $this->fileType  = $fileType;
            $this->fileSize  = $fileSize;
            $this->width     = $makeImg->width();
            $this->height    = $makeImg->height();
            $this->isRemote  = 0;
            if(!Storage::makeDirectory($this->fileArea.$this->timePath)){
                return false;
            }
            $makeImg->save(public_path($this->url).$this->fileName,$this->percent);
            $this->save();
            return $this;
        } catch (\Exception $e) {
            Log::error('【'.$e->getMessage().'】'.'【'.$e->getFile().'】'.'【'.$e->getTraceAsString ().'】');
            return false;
        }
    }

    /**
     * 上传文件
     * @param  [type] $request [description]
     * @return [type]          [description]
     */
    function uploadFile($request){
        $data = $request->all();
        $validator = $this->fileValidator($data);
        if($validator->fails()){
            if($validator->fails()){
                $this->jsonData['code'] = 1;
                $this->jsonData['msg'] = $validator->errors()->first();
                exit(json_encode($this->jsonData));
            }
        }
        if($request->hasFile($this->uploadFileName) && $request->file($this->uploadFileName)->isValid()){
            try {
                $file = $request->file($this->uploadFileName);
                $fileSize = $file->getClientSize();
                if($fileSize/1024>$this->fileMaxSize){
                    $this->jsonData['code'] = 1;
                    $this->jsonData['msg'] = '图片上传过大,只允许'.($this->picMaxSize/1024).'mb内的图片';
                    exit(json_encode($this->jsonData));
                }
                $fileArea = isset($data['fileArea']) ?  $data['fileArea'].'/' : '';

                $filePath  = date('Y',time()).'/'.date('m',time()).'/'.date('d',time())."/".date('H',time()).'/';
                $fileName              = date('YmdHis').str_random(15).'.'.$file->getClientOriginalExtension();

                $this->url       = $this->rootName.$fileArea.$filePath;
                $this->remoteUrl = '';
                $this->fileType  = $file->getClientMimeType();
                $this->fileName  = $fileName;
                $this->fileSize  = $fileSize;
                $this->isRemote = 0;
                $url = $fileArea.'/'.$filePath.$fileName;

                Storage::put($url,file_get_contents($file));
                $this->save();
                return $this;
            } catch (\Exception $e) {
                Log::error('【'.$e->getMessage().'】'.'【'.$e->getFile().'】'.'【'.$e->getTraceAsString ().'】');
                $this->jsonData['code'] = 1;
                $this->jsonData['msg'] = '上传文件异常';
                exit(json_encode($this->jsonData));
            }
        }
    }

    /**
     * 上传视频
     * @param  [type] $request [description]
     * @return [type]          [description]
     */
    function uploadVideo($request){
        $data = $request->all();
        $validator = $this->videoValidator($data);
        if($validator->fails()){
            if($validator->fails()){
                $this->jsonData['code'] = 1;
                $this->jsonData['msg'] = $validator->errors()->first();
                exit(json_encode($this->jsonData));
            }
        }
        if($request->hasFile($this->uploadVideoName) && $request->file($this->uploadVideoName)->isValid()){
            try {
                $file = $request->file($this->uploadVideoName);
                $fileSize = $file->getClientSize();
                if($fileSize/1024>$this->videoMaxSize){
                    $this->jsonData['code'] = 1;
                    $this->jsonData['msg'] = '视频上传过大,只允许'.($this->picMaxSize/1024).'mb内的图片';
                    exit(json_encode($this->jsonData));
                }
                $fileArea = isset($data['fileArea']) ?  $data['fileArea'].'/' : '';

                $filePath  = date('Y',time()).'/'.date('m',time()).'/'.date('d',time())."/".date('H',time()).'/';
                $fileName              = date('YmdHis').str_random(15).'.'.$file->getClientOriginalExtension();

                $this->url       = $this->rootName.$fileArea.$filePath;
                $this->remoteUrl = '';
                $this->fileType  = $file->getClientMimeType();
                $this->fileName  = $fileName;
                $this->fileSize  = $fileSize;
                $this->isRemote = 0;
                $url = $fileArea.'/'.$filePath.$fileName;

                Storage::put($url,file_get_contents($file));
                $this->save();
                return $this;
            } catch (\Exception $e) {
                Log::error('【'.$e->getMessage().'】'.'【'.$e->getFile().'】'.'【'.$e->getTraceAsString ().'】');
                $this->jsonData['code'] = 1;
                $this->jsonData['msg'] = '上传视频异常';
                exit(json_encode($this->jsonData));
            }
        }
    }

    /**
     * 文件验证
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    private function fileValidator(array $data){
        $attribute =  array(
            $this->uploadFileName => '文件',
        );

        $message  = array(
            'required' => ':attribute必须上传',
            'mimes' => '请上传指定类型文件'
        );

        return Validator::make($data, [
            $this->uploadFileName => 'bail|required|mimes:xls,xlsx,doc,ppt,pdf,csv,txt',
        ],$message,$attribute);
    }

    /**
     * 视频验证
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    private function videoValidator(array $data){
        $attribute =  array(
            $this->uploadVideoName => '视频',
        );

        $message  = array(
            'required' => ':attribute必须上传',
            'mimes' => '请上传指定类型文件'
        );

        return Validator::make($data, [
            $this->uploadVideoName => 'bail|required|mimes:mp4',
        ],$message,$attribute);
    }

    /**
     * 图片验证
     * @param  array  $data [description]
     * @return [type]       [description]
     */
    private function picValidator(array $data){
        $attribute =  array(
            $this->uploadPicName => '图片',
        );

        $message  = array(
            'required' => ':attribute必须上传',
            'image' => '请上传jpeg、png格式的图片',
        );

        return Validator::make($data, [
            $this->uploadPicName => 'bail|required|image',
        ],$message,$attribute);
    }
}
